﻿Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.Specialized
Imports System.ComponentModel.DataAnnotations
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Web.DynamicData
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Reflection

Partial Public Class Search
    Inherits System.Web.DynamicData.QueryableFilterUserControl

    Public Overrides Function GetQueryable(source As IQueryable) As IQueryable
        If (Column.TypeCode <> TypeCode.String) Then
            Return source
        End If

        Dim searchString As String = Me.TextBox1.Text
        If (TextBox1.Text = "") Then
            searchString = String.Empty
        End If
        Dim type As Type = GetType(String)

        Dim searchProperty As String = Column.DisplayName
        Dim searchFilter As ConstantExpression = Expression.Constant(searchString)

        Dim parameter As ParameterExpression = Expression.Parameter(source.ElementType)
        Dim prop As MemberExpression = Expression.Property(parameter, Me.Column.Name)

        If (Nullable.GetUnderlyingType(prop.Type) <> Nothing) Then
            prop = Expression.Property(prop, "Value")
        End If

        Dim method As MethodInfo = GetType(String).GetMethod("Contains", New Type() {GetType(String)})

        Dim containsMethodExp = Expression.Call(prop, method, searchFilter)
        Dim containsLambda = Expression.Lambda(containsMethodExp, parameter)


        Dim resultExpression = Expression.Call(GetType(Queryable), "Where", New Type() {source.ElementType}, source.Expression, Expression.Quote(containsLambda))

        Return source.Provider.CreateQuery(resultExpression)
    End Function

    Protected Sub Button1_Click(sender As Object, e As EventArgs)
        OnFilterChanged()
    End Sub
End Class